package com.zgg.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import com.zgg.config.AliOssProperties;
import com.zgg.files.bean.OSSFile;
import com.zgg.utils.aliOss.AliOssImage;
import com.zgg.utils.aliOss.AliOssImageConfig;
import com.zgg.utils.aliOss.AliOssImageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2017/8/23 0023.
 */
public class AliOssUtils extends Thread {
    private static final Logger logger = LoggerFactory.getLogger(AliOssUtils.class);
    //外网访问地址
    private static String endpoint = "";
    //
    private static String accessKeyId = "";
    //
    private static String accessKeySecret = "";
    //存储空间名
    private static String bucketName = "";
    //并发数
    private static int taskNum = 5;
    //分片大小
    private static long partSize = 1024 * 1024 * 1;
    //是否开启断点续传
    private static boolean isCheckPoint = true;
    private static int max = 0;

    private static int imgWidth = 600;
    private static int imgHeight = 400;
    //过期时间（按秒计算）
    private static int expirTime = 60 * 60;

    private static OSS ossClient;


    private static ExecutorService pool;
    private static final int threadSize = 10;

    @Autowired
    private static RedisUtils redisUtils;

    /**
     * 初始化oss配置参数
     *
     * @param aliOssProperties
     */
    private static void initConfig(AliOssProperties aliOssProperties) {
        if (bucketName == null || "".equals(bucketName)) {
            bucketName = aliOssProperties.getBucketName();
        }
        if (endpoint == null || "".equals(endpoint)) {
            endpoint = aliOssProperties.getEndpoint();
        }
        if (accessKeyId == null || "".equals(accessKeyId)) {
            accessKeyId = aliOssProperties.getAccessKeyId();
        }
        if (accessKeySecret == null || "".equals(accessKeySecret)) {
            accessKeySecret = aliOssProperties.getAccessKeySecret();
        }
        if (max == 0) {
            max = aliOssProperties.getMaxKeys();
        }
    }

    /**
     * 初始化线程池
     *
     * @param size
     */
    private static void initThreadPool(int size) {
        int taskSize = threadSize > size ? threadSize : size;
        if (pool == null) {
            pool = Executors.newFixedThreadPool(taskSize);
        }
    }

    /**
     * 线程池关闭
     *
     * @throws Exception
     */
    private static void closeThreadPool() throws Exception {
        if (pool != null) {
            pool.shutdown();
        } else {
            logger.error("======>>>>>   线程池为空");
            throw new Exception("Thread Pool is null");
        }
    }


    /**
     * 获得ossclient
     *
     * @param aliOssProperties
     * @return
     */
    private static OSS getOssClient(AliOssProperties aliOssProperties) {
        initConfig(aliOssProperties);
        if (ossClient == null) {
            return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        }
        return ossClient;
    }

    /**
     * 初始化简单上传配置
     *
     * @param ossFilePath
     * @return
     */
    private static PutObjectRequest putObjectInitConfig(String ossFilePath, String localFileName, Callback callback) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossFilePath, new File(localFileName));
        if (callback != null) {
            putObjectRequest.setCallback(callback);
        }
        return putObjectRequest;
    }

    /**
     * 初始化断点续传配置
     *
     * @param uploadFile
     * @return
     */
    private static UploadFileRequest uploadInitconfig(String uploadFile, Callback callback) {
        UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, uploadFile);
        // 待上传的本地文件
        uploadFileRequest.setUploadFile(uploadFile);
        // 设置并发下载数，默认1
        uploadFileRequest.setTaskNum(taskNum);
        // 设置分片大小，默认100KB
        uploadFileRequest.setPartSize(partSize);
        // 开启断点续传，默认关闭
        uploadFileRequest.setEnableCheckpoint(isCheckPoint);
        if (callback != null) {
            uploadFileRequest.setCallback(callback);
        }
        return uploadFileRequest;
    }

    /**
     * 实现多线程，并掉用上传方法
     */
    static class UploadOSSFileCallable implements Callable {
        private String fileName;
        private String fileId;

        private AliOssProperties aliOssProperties;
        private JSONObject callBackJson;

        UploadOSSFileCallable(String fileName, String fileId, AliOssProperties aliOssProperties, JSONObject callbackJson) {
            this.fileName = fileName;
            this.fileId = fileId;
            this.aliOssProperties = aliOssProperties;
            this.callBackJson = callbackJson;
        }

        @Override
        public Object call() throws Exception {
            uploadOSSFile(this.fileName, this.fileId, this.aliOssProperties, this.callBackJson);
            return null;
        }
    }

    /**
     * 下载文件并打成zip包。
     *
     * @param filePaths
     * @param outFilePath
     * @param aliOssProperties
     * @return
     */
    public static String downFileAndZip(List<OSSFile> filePaths, String outFilePath, AliOssProperties aliOssProperties) {
        long time = System.currentTimeMillis();
        String fileName = outFilePath + time + ".zip";
        ZipOutputStream zos = null;
        try {
            FileOutputStream f = new FileOutputStream(fileName);
            FileUtils.createFile(fileName);
            /**
             * 作用是为任何OutputStream产生校验和
             * 第一个参数是制定产生校验和的输出流，第二个参数是指定Checksum的类型 （Adler32（较快）和CRC32两种）
             */
            CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
            // 用于将数据压缩成Zip文件格式
            zos = new ZipOutputStream(csum);
            OSS ossClient = getOssClient(aliOssProperties);

            for (OSSFile ossfile : filePaths) {
                if (isValiFile(ossfile.getFpath(), aliOssProperties)) {
                    // 获取Object，返回结果为OSSObject对象
                    OSSObject ossObject = ossClient.getObject(aliOssProperties.getBucketName(), ossfile.getFpath());
                    // 读去Object内容  返回
                    InputStream inputStream = ossObject.getObjectContent();

                    // 对于每一个要被存放到压缩包的文件，都必须调用ZipOutputStream对象的putNextEntry()方法，确保压缩包里面文件不同名
                    zos.putNextEntry(new ZipEntry(ossfile.getFname()));
                    int bytesRead = 0;
                    // 向压缩文件中输出数据
                    while ((bytesRead = inputStream.read()) != -1) {
                        zos.write(bytesRead);
                    }
                    inputStream.close();
                    // 当前文件写完，定位为写入下一条项目
                    zos.closeEntry();
                } else {
                    logger.error("=========>>>>>   【" + ossfile + "】不存在，请重新确认！");
                }
            }

            zos.close();
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 下载文件并临时存放在服务器上。
     *
     * @param ossFile
     * @param outFilePath
     * @param aliOssProperties
     * @return
     */
    public static String downFileStream(OSSFile ossFile, String outFilePath, AliOssProperties aliOssProperties) {
        logger.info("==================>    批量下载启动....");
        long startTime = System.currentTimeMillis();
        OSS ossClient = getOssClient(aliOssProperties);
        String downLoadFile = "";
        if (isValiFile(ossFile.getFpath(), aliOssProperties)) {

            downLoadFile = outFilePath + ossFile.getFname();//file[file.length - 1];

            FileUtils.createFile(downLoadFile);

            DownloadFileRequest downloadFileRequest = new DownloadFileRequest(aliOssProperties.getBucketName(), ossFile.getFpath());
            downloadFileRequest.setDownloadFile(downLoadFile);
            downloadFileRequest.setPartSize(aliOssProperties.getPartSize());
            downloadFileRequest.setTaskNum(aliOssProperties.getTaskNum());
            downloadFileRequest.setEnableCheckpoint(aliOssProperties.getCheckPoint());

            // 下载文件。
            DownloadFileResult downloadRes = null;
            //objectMetadata = null;
            try {
                downloadRes = ossClient.downloadFile(downloadFileRequest);

                // 下载成功时，会返回文件元信息。
                ObjectMetadata objectMetadata = downloadRes.getObjectMetadata();
                logger.error("");

            } catch (Throwable throwable) {
                throwable.printStackTrace();
                logger.error("=========>>>>>>     下载文件失败！");
            }
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        long endTime = System.currentTimeMillis();
        logger.info("==================>    下载时间：【" + (endTime - startTime) + "】");
        //返回文件路径
        return downLoadFile;
    }

    /**
     * 批量上传文件
     * 一次性最多上传10个文件
     *
     * @param fileNameMap
     * @return
     */
    public static void upLoadOSSFileList(Map<String, String> fileNameMap, AliOssProperties aliOssProperties, JSONObject callbackJson) {
        logger.info("==================>    批量上传启动....");
        //线程池大小
        initThreadPool(10);
        Set<String> keySet = fileNameMap.keySet();
        for (String fileName : keySet) {
            Callable callable = new UploadOSSFileCallable(fileName, fileNameMap.get(fileName), aliOssProperties, callbackJson);
            // 执行任务并获取Future对象
            pool.submit(callable);
        }
        logger.info("==================>    批量上传结束....");
    }


    private static void uploadOSSFile(String uploadFilePath, String fileId, AliOssProperties aliOssProperties, JSONObject clientCallbackJson) {
        long startTime = System.currentTimeMillis();
        OSS ossClient = getOssClient(aliOssProperties);

        JSONObject callbackJson = new JSONObject();

        callbackJson.put("fileName", uploadFilePath);
        callbackJson.put("fileId", fileId);
        if (clientCallbackJson.containsKey("callbackBody")) {
            callbackJson.put("clientCallBackBody", clientCallbackJson.get("callbackBody"));
        }

        //创建callback对象
        Callback callback = getCallBack(aliOssProperties, callbackJson);

        //当文件小于20MB的时候，使用简单上传，否则使用分片断点续传
        if (FileUtils.fileLengthByMB(uploadFilePath) < 2) {
            //  当文件小于2MB调用postObject
            putObjectFile(ossClient, uploadFilePath, callback);
        } else {
            //  当文件大于2MB调用分片断点续传
            upLoadOSSFile(ossClient, uploadFilePath, callback);
        }
        long endTime = System.currentTimeMillis();
        logger.error("=============>>>>>>        文件【" + uploadFilePath + "】上传到oss的时间：【" + (endTime - startTime) + "】ms");
    }

    /**
     * 配置回调方法
     *
     * @param aliOssProperties
     * @return
     */
    private static Callback getCallBack(AliOssProperties aliOssProperties, JSONObject callbackJson) {
        Callback callback = null;
        //当配置文件里回调开关打开时，上传功能使用回调
        if (aliOssProperties.getCallBackSwitch()) {
            callback = new Callback();
            callback.setCallbackUrl(aliOssProperties.getCallbackUrl());
            callback.setCallbackHost(aliOssProperties.getCallbackHost());

            String callBackBodyType = aliOssProperties.getCallbackBodyType();

            StringBuffer stringBuffer = new StringBuffer();

            //配置回调参数
            if (callBackBodyType != null && "json".equals(callBackBodyType)) {
                callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
                //创建callBackBody   json
                stringBuffer.append("{").append("\\\"bucket\\\":${bucket}");
                stringBuffer.append(",").append("\\\"object\\\":${object}");
                stringBuffer.append(",").append("\\\"mimeType\\\":${mimeType}");
                stringBuffer.append(",").append("\\\"size\\\":${size}");
                stringBuffer.append(",").append("\\\"fileName\\\":${x:fileName}");
                stringBuffer.append(",").append("\\\"fileId\\\":${x:fileId}");
                stringBuffer.append(",").append("\\\"clientCallBackBody\\\":${x:clientCallBackBody}");
                stringBuffer.append("}");

                logger.error("===========>>>>>  json  " + stringBuffer.toString());

            } else if (callBackBodyType != null && "urlencode".equals(callBackBodyType)) {
                callback.setCalbackBodyType(Callback.CalbackBodyType.URL);
                //创建callBackBody x-www-form-urlencoded方式
                stringBuffer.append("bucket=").append("${bucket}");
                stringBuffer.append("&").append("object=").append("${object}");
                stringBuffer.append("&").append("mimeType=").append("${mimeType}");
                stringBuffer.append("&").append("size=").append("${size}");
                stringBuffer.append("&").append("fileName=").append("${x:fileName}");
                stringBuffer.append("&").append("fileId=").append("${x:fileId}");
                stringBuffer.append("&").append("clientCallBackBody=").append("${x:clientCallBackBody}");

                logger.warn("===========>>>>>  url  " + stringBuffer.toString());
            }
            callback.addCallbackVar("x:fileName", callbackJson.getString("fileName"));
            callback.addCallbackVar("x:fileId", callbackJson.getString("fileId"));
            callback.addCallbackVar("x:clientCallBackBody", callbackJson.getString("clientCallBackBody"));
            callback.setCallbackBody(stringBuffer.toString());
        }
        return callback;
    }

    /**
     * 简单上传
     *
     * @param ossClient
     * @param fileName
     * @param callback
     * @return
     */
    private static void putObjectFile(OSS ossClient, String fileName, Callback callback) {
        try {
            String ossFilePath = StringUtils.generateOssKey(fileName);
            PutObjectResult putObjectResult = ossClient.putObject(putObjectInitConfig(ossFilePath, fileName, callback));
            logger.info("==========>>>   文件上传成功");
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
            logger.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
            logger.error("Error Message:    【" + oe.getMessage() + "】");
            logger.error("Error Code:       【" + oe.getErrorCode() + "】");
            logger.error("Request ID:       【" + oe.getRequestId() + "】");
            logger.error("Host ID:          【" + oe.getHostId() + "】");
            logger.error("失败的文件名:     【" + fileName + "】");
        } catch (ClientException ce) {
            logger.error(ce.getMessage());
            logger.error("Caught an ClientException, which means the client encountere a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
            logger.error("Error Message:    【" + ce.getMessage() + "】");
            logger.error("失败的文件名:     【" + fileName + "】");
        } finally {
            ossClient.shutdown();
        }

    }

    /**
     * 分片断点续传
     *
     * @param ossClient
     * @param fileName
     * @param callback
     * @return
     */
    private static void upLoadOSSFile(OSS ossClient, String fileName, Callback callback) {
        try {
            String filepath = StringUtils.generateOssKey(fileName);
            UploadFileResult uploadResult = ossClient.uploadFile(uploadInitconfig(filepath, callback));
            logger.info("==========>>>   文件上传成功");
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
            logger.error("Error Message:    【" + oe.getMessage() + "】");
            logger.error("Error Code:       【" + oe.getErrorCode() + "】");
            logger.error("Request ID:       【" + oe.getRequestId() + "】");
            logger.error("Host ID:          【" + oe.getHostId() + "】");
            logger.error("失败的文件名:     【" + fileName + "】");
        } catch (ClientException ce) {
            logger.error(ce.getMessage());
            logger.error("Caught an ClientException, which means the client encountere a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
            logger.error("Error Message:    【" + ce.getMessage() + "】");
            logger.error("失败的文件名:     【" + fileName + "】");
        } catch (Throwable throwable) {
            logger.error("失败的文件名:     【" + fileName + "】");
            throwable.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }


    /**
     * 判断Bucket是否存在
     *
     * @param bucket
     * @return
     */
    public static boolean isValiBucket(String bucket, AliOssProperties aliOssProperties) {
        OSS ossClient = getOssClient(aliOssProperties);
        boolean flag = ossClient.doesBucketExist(bucket);
        ossClient.shutdown();
        return flag;
    }

    /**
     * 判断文件是否存在
     *
     * @param fileName
     * @return
     */
    private static boolean isValiFile(String bucket, String fileName, AliOssProperties aliOssProperties) {
        boolean flag = false;
        OSS ossClient = getOssClient(aliOssProperties);
        if (bucket == null || "".equals(bucket)) {
            bucket = bucketName;
        }
        flag = ossClient.doesObjectExist(bucket, fileName);
        ossClient.shutdown();
        return flag;
    }

    /**
     * 判断文件是否存在
     *
     * @param fileName
     * @return
     */
    public static boolean isValiFile(String fileName, AliOssProperties aliOssProperties) {
        return isValiFile(null, fileName, aliOssProperties);
    }

    /**
     * 获得oss上指定path下的文件
     * 默认一百条数据
     *
     * @param bucket
     * @param path
     * @param maxKeys
     */
    private static List<String> getOssFileList(String bucket, String path, int maxKeys, AliOssProperties
            aliOssProperties) {
        OSS ossClient = getOssClient(aliOssProperties);
        if (bucket == null || "".equals(bucket)) {
            bucket = bucketName;
        }
        ObjectListing objectListing = ossClient.listObjects(bucket, path);
        if (maxKeys == 0) {
            maxKeys = max;
        }
        objectListing.setMaxKeys(maxKeys);
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        List<String> list = new ArrayList<>();
        for (OSSObjectSummary sum : sums) {
            list.add(sum.getKey());
        }
        return list;
    }

    /**
     * 获得oss上指定path下的文件
     * 默认一百条数据
     *
     * @param path
     * @param maxKeys
     */
    public static List<String> getOssFileList(String path, int maxKeys, AliOssProperties aliOssProperties) {
        return getOssFileList(null, path, max, aliOssProperties);
    }

    /**
     * 获得oss上指定path下的文件
     * 默认一百条数据
     *
     * @param path
     */
    public static List<String> getOssFileList(String path, AliOssProperties aliOssProperties) {
        return getOssFileList(null, path, max, aliOssProperties);
    }

    /**
     * 批量删除oss文件
     *
     * @param bucket
     * @param fileList
     */
    public static List<String> delOssFiles(String bucket, List<String> fileList, AliOssProperties aliOssProperties) {
        OSS ossClient = getOssClient(aliOssProperties);
        if (bucket == null || "".equals(bucket)) {
            bucket = bucketName;
        }
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucket).withKeys(fileList).withQuiet(true));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        // 关闭client
        ossClient.shutdown();
        return deletedObjects;
    }

    /**
     * 批量删除oss文件
     *
     * @param fileList
     */
    public static List<String> delOssFile(List<String> fileList, AliOssProperties aliOssProperties) {
        return delOssFiles(null, fileList, aliOssProperties);
    }

    /**
     * 删除oss单个文件
     *
     * @param bucket
     * @param fileName
     */
    public static void delOssFile(String bucket, String fileName, AliOssProperties aliOssProperties) {
        List<String> list = new ArrayList<>();
        list.add(fileName);
        List<String> resultList = delOssFiles(bucket, list, aliOssProperties);
        if (resultList.size() > 0) {
            for (int i = 0; i < 5; i++) {
                delOssFile(bucket, fileName, aliOssProperties);
            }
            logger.error("文件：【" + fileName + "】连续5次删除失败，请检查原因！");
        }
    }

    /**
     * 删除oss单个文件
     *
     * @param fileName
     */
    public static void delOssFile(String fileName, AliOssProperties aliOssProperties) {
        delOssFile(null, fileName, aliOssProperties);
    }

    /**
     * 拷贝oss 文件
     *
     * @param bucket
     * @param fileName
     * @param destBucket
     * @param destFileName
     */
    public static void copyOssFile(String bucket, String fileName, String destBucket, String
            destFileName, AliOssProperties aliOssProperties) {
        OSS ossClient = getOssClient(aliOssProperties);
        CopyObjectResult result = ossClient.copyObject(bucket, fileName, destBucket, destFileName);
        logger.info("================>>>>>>>      ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
        // 关闭client
        ossClient.shutdown();
    }

    /**
     * 从oss上获取文件的访问路径。
     * 每个文件都需要获得权限才能访问。
     * 默认的过期时间是一个小时
     *
     * @param bucket
     * @param fileName
     * @param time
     * @return
     */
    private static Map<String, String> getImageUrl(String bucket, List<String> fileName, int time, AliOssProperties aliOssProperties) {
        OSS ossClient = getOssClient(aliOssProperties);
        Map<String, String> urlMap = new HashMap<>();
        if (time <= 0) {
            time = 60 * 60;
        }
        Date expiration = new Date(System.currentTimeMillis() + time * 1000);
        if (bucket == null || "".equals(bucket)) {
            bucket = bucketName;
        }
        for (String s : fileName) {
            URL url = ossClient.generatePresignedUrl(bucket, s, expiration);
            urlMap.put(s, url.toString());
        }
        return urlMap;
    }

    /**
     * 获得图片文件的访问路径
     * 默认是一小时
     *
     * @param bucket
     * @param fileName
     * @param time
     * @return
     */
    public static String getImageUrl(String bucket, String fileName, int time, AliOssProperties aliOssProperties) {
        List<String> list = new ArrayList<>();
        list.add(fileName);
        Map<String, String> map = getImageUrl(bucket, list, time, aliOssProperties);
        return map.get(fileName);
    }

    /**
     * 获得图片文件的访问路径
     * 默认是一小时
     *
     * @param fileName
     * @param time
     * @return
     */
    public static String getImageUrl(String fileName, int time, AliOssProperties aliOssProperties) {
        return getImageUrl(null, fileName, time, aliOssProperties);
    }

    /**
     * 获得图片文件的访问路径
     * 默认是一小时
     *
     * @param fileName
     * @return
     */
    public static String getImageUrl(String fileName, AliOssProperties aliOssProperties) {
        return getImageUrl(null, fileName, 0, aliOssProperties);
    }

    /**
     * 批量获取文件的访问路径
     *
     * @param bucket
     * @param fileNames
     * @param time
     * @return
     */
    public static Map<String, String> getImageUrlList(String bucket, List<String> fileNames,
                                                      int time, AliOssProperties aliOssProperties) {
        Map<String, String> urlMap = getImageUrl(bucket, fileNames, time, aliOssProperties);
        return urlMap;
    }

    /**
     * 批量获取文件的访问路径
     *
     * @param fileNames
     * @param time
     * @return
     */
    public static Map<String, String> getImageUrlList(List<String> fileNames, int time, AliOssProperties
            aliOssProperties) {
        Map<String, String> urlMap = getImageUrl(null, fileNames, time, aliOssProperties);
        return urlMap;
    }

    /**
     * 批量获取文件的访问路径
     *
     * @param fileNames
     * @return
     */
    public static Map<String, String> getImageUrlList(List<String> fileNames, AliOssProperties aliOssProperties) {
        Map<String, String> urlMap = getImageUrl(null, fileNames, 0, aliOssProperties);
        return urlMap;
    }

    /**
     * 返回压缩图片访问url
     *
     * @param bucket
     * @param fileNames
     * @param processConfig
     * @param time
     */
    public static Map<String, String> imageProcess(String
                                                           bucket, List<String> fileNames, List<AliOssImageConfig> processConfig, int time, AliOssProperties
                                                           aliOssProperties) {
        OSS ossClient = getOssClient(aliOssProperties);
        StringBuffer style = new StringBuffer();
        if (bucket == null || "".equals(bucket)) {
            bucket = bucketName;
        }
        //图片处理样式
        if (processConfig != null) {
            for (AliOssImageConfig aliOssImageConfig : processConfig) {
                AliOssImage aliOssImage = AliOssImageFactory.createAliOssImage(aliOssImageConfig);
                style.append(aliOssImage.operatingString(aliOssImageConfig));
            }
        }
        //过期时间
        if (time == 0) {
            time = expirTime;
        }
        Date expiration = new Date(System.currentTimeMillis() + 1000 * time);
        Map<String, String> fileMap = new HashMap<>();

        //RedisUtils redisUtils = RedisUtils.getInstance();
        for (String fileName : fileNames) {
            if (fileName != null || !"".equals(fileName)) {
                String url = new String();
                //图片路径缓存
                //if (!redisUtils.exists(StaticResource.SYS_CACHE_IMAGE_URL + fileName)) {
                String[] styleArr = style.toString().split("/");
                if ("image".equals(styleArr[0])) {
                    //获得访问路径
                    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, fileName, HttpMethod.GET);
                    request.setProcess(style.toString());
                    request.setExpiration(expiration);
                    url = ossClient.generatePresignedUrl(request).toString();
                }
                if ("style".equals(styleArr[0])) {
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append("http://").append(bucket).append(".").append(endpoint).append("/").append(fileName).append("/").append(styleArr[1]);
                    url = stringBuffer.toString();
                }
                ////将图片访问路径给缓存起来
                //redisUtils.set(StaticResource.SYS_CACHE_IMAGE_URL + fileName, url);
                //redisUtils.expire(StaticResource.SYS_CACHE_IMAGE_URL + fileName, 3300);
                //} else {
                //    url = redisUtils.getString(StaticResource.SYS_CACHE_IMAGE_URL + fileName);
                //}

                fileMap.put(fileName, url);
            } else {
                logger.info("=====================>>>>>>>>    文件名为空！！！");
            }
        }

        ossClient.shutdown();
        return fileMap;

    }

    /**
     * 返回压缩图片访问url
     *
     * @param fileNames
     * @param processConfig
     * @return
     */
    public static String imageProcess(String bucket, String fileNames, AliOssImageConfig processConfig,
                                      int time, AliOssProperties aliOssProperties) {
        List<String> fileNameList = new ArrayList<>();
        fileNameList.add(fileNames);
        List<AliOssImageConfig> aliOssImageConfigList = new ArrayList<>();
        aliOssImageConfigList.add(processConfig);
        Map<String, String> urlMap = imageProcess(bucket, fileNameList, aliOssImageConfigList, time, aliOssProperties);
        String url = new String();
        Set<String> keySet = urlMap.keySet();
        for (String s : keySet) {
            url = urlMap.get(s);
        }
        return url;
    }

    /**
     * 返回压缩图片访问url
     *
     * @param fileNames
     * @param processConfig
     * @param time
     * @return
     */
    public static String imageProcess(String fileNames, AliOssImageConfig processConfig, int time, AliOssProperties
            aliOssProperties) {
        return imageProcess(null, fileNames, processConfig, time, aliOssProperties);
    }

    /**
     * 返回压缩图片访问url
     *
     * @param fileNames
     * @param processConfig
     * @return
     */
    public static String imageProcess(String fileNames, AliOssImageConfig processConfig, AliOssProperties
            aliOssProperties) {
        return imageProcess(null, fileNames, processConfig, 0, aliOssProperties);
    }

    /**
     * 返回压缩图片访问url
     *
     * @param fileNames
     * @param processConfig
     * @param time
     * @return
     */
    public static Map<String, String> imageProcess
    (List<String> fileNames, List<AliOssImageConfig> processConfig, int time, AliOssProperties aliOssProperties) {
        return imageProcess(null, fileNames, processConfig, time, aliOssProperties);
    }

    /**
     * 返回压缩图片访问url
     *
     * @param fileNames
     * @param processConfig
     * @return
     */
    public static Map<String, String> imageProcess
    (List<String> fileNames, List<AliOssImageConfig> processConfig, AliOssProperties aliOssProperties) {
        return imageProcess(null, fileNames, processConfig, 0, aliOssProperties);
    }

    /**
     * 返回压缩图片访问url
     *
     * @param fileNames
     * @return
     */
    public static Map<String, String> imageProcess(List<String> fileNames, AliOssProperties aliOssProperties) {
        return imageProcess(null, fileNames, new ArrayList<AliOssImageConfig>(), 0, aliOssProperties);
    }
}
